using System;
using System.Collections.Generic;
using Suk.Common;
using Suk.Interface;
using Suk.Interface.Admin;
using Suk.Models;
using Suk.Models.Admin;

namespace Suk.Service.Admin
{
    public class MenuService : BaseService<Menu>, IMenuInterface
    {


        public override List<Menu> FindEntity(Menu m, ref int totalCount, int pageIndex = 1, int pageSize = 10)
        {

            int UserGroupId = m.UserGroupId;
            if (UserGroupId == 0 || UserGroupId == 9999)
            {
                return base.FindEntity(ref totalCount, pageIndex, pageSize);
            }
            else
            {
                var allSchools = db.Queryable<MenuGroupRelation>().Where(t => t.UserGroupId == UserGroupId).ToList();
                var list = db.Queryable<Menu>().ToPageList(pageIndex, pageSize);
                foreach (Menu it in list)
                {
                    foreach (MenuGroupRelation dd in allSchools)
                    {
                        if (dd.menuId == it.menuId)
                        {
                            it.UserGroupId = dd.UserGroupId;
                        }
                    }
                }

                return list;
            }
        }

        public List<Menu> FindMenu()
        {
            string sql = @"
            select a.* from Menu a left join MenuGroupRelation b on a.menuId=b.menuId
left join UserGroupRelation c on c.UserGroupId=b.UserGroupId
left join [User] d on c.UserId=d.id
where d.code='001'
            ";
            List<Menu> list = db.SqlQueryable<Menu>(sql).ToList();
            return list;
        }
        public readonly Guid guid=Guid.NewGuid();
        public Guid GetGuid()
        {
            return guid;
        }

        public int MenuGroupRelationUpdate(Menu model)
        {
            int count = 0;

            MenuGroupRelation m = db.Queryable<MenuGroupRelation>()
            .Where(t => t.UserGroupId == model.UserGroupId & t.menuId == model.menuId)
            .Single();

            if (m == null)
            {
                m = new MenuGroupRelation();
                m.UserGroupId = model.UserGroupId;
                m.menuId = model.menuId;
                m.CreateTime = DateTime.Now;
            }

            if (model.IsTrue == 0)
            {
                count = db.Deleteable(m).ExecuteCommand();
            }
            else
            {
                count = db.Saveable(m).ExecuteCommand();
            }


            return count;

        }


    }
}
